package com.hktf.corelib.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;


import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.List;

public class LogUtils6 {
	/** 日志输出级别NONE */
	private static final int LEVEL_NONE = 0;
	/** 日志输出级别V */
	private static final int LEVEL_VERBOSE = 1;
	/** 日志输出级别D */
	private static final int LEVEL_DEBUG = 2;
	/** 日志输出级别I */
	private static final int LEVEL_INFO = 3;
	/** 日志输出级别W */
	private static final int LEVEL_WARN = 4;
	/** 日志输出级别E */
	private static final int LEVEL_ERROR = 5;

	/** 日志输出时的TAG */
	private static String mTag = "cdz";
	/** 是否允许出log */
	private static int mDebuggable = LEVEL_ERROR;

	/** 用于记时的变量 */
	private static long mTimestamp = 0;
	/** 写文件的锁对象 */
	private static final Object mLogLock = new Object();

	public static boolean saveLog=false;


	public static boolean isTest(){
		if(mDebuggable==LEVEL_ERROR){
			return true;
		}
		return false;

	}

	/** 以级别为 d 的形式输出LOG */
	public static void v(String msg) {
		if (mDebuggable >= LEVEL_VERBOSE) {
			Log.v(mTag, msg);
		}
	}

	/** 以级别为 d 的形式输出LOG */
	public static void d(String msg) {
		if (mDebuggable >= LEVEL_DEBUG) {
			Log.d(mTag, msg);
		}
	}

	/** 以级别为 i 的形式输出LOG */
	public static void i(String msg) {
		if (mDebuggable >= LEVEL_INFO) {
			Log.i(mTag, msg);
		}
	}

	/** 以级别为 w 的形式输出LOG */
	public static void w(String msg) {
		if (mDebuggable >= LEVEL_WARN) {
			Log.w(mTag, msg);
		}
	}

	/** 以级别为 w 的形式输出Throwable */
	public static void w(Throwable tr) {
		if (mDebuggable >= LEVEL_WARN) {
			Log.w(mTag, "", tr);
		}
	}

	/** 以级别为 w 的形式输出LOG信息和Throwable */
	public static void w(String msg, Throwable tr) {
		if (mDebuggable >= LEVEL_WARN && null != msg) {
			Log.w(mTag, msg, tr);
		}
	}

	/** 以级别为 e 的形式输出LOG */
	public static void e(String msg) {
		if (mDebuggable >= LEVEL_ERROR) {
			Log.e(mTag, msg);
		}
	}

	/** 以级别为 e 的形式输出Throwable */
	public static void e(Throwable tr) {
		if (mDebuggable >= LEVEL_ERROR) {
			Log.e(mTag, "", tr);
		}
	}

	/** 以级别为 e 的形式输出LOG信息和Throwable */
	public static void e(String msg, Throwable tr) {
		if (mDebuggable >= LEVEL_ERROR && null != msg) {
			Log.e(mTag, msg, tr);
		}
	}

	/**
	 * 把Log存储到文件中
	 * 
	 * @param log
	 *            需要存储的日志
	 * @param path
	 *            存储路径
	 */
	public static void log2File(String log, String path) {
		log2File(log, path, true);
	}

	public static void log2File(String log, String path, boolean append) {
		synchronized (mLogLock) {
			FileUtils.writeFile(log + "\r\n", path, append);
		}
	}
	private static void saveLog(){

	}
	private static String logFileName;//日志文件名称

	public static String getLogFileName() {
		if (logFileName == null) {
			long l = System.currentTimeMillis();
			SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd_HHmmss");
			logFileName=format.format(l)+"_log.txt";
		}
		return logFileName;
	}
	private static Handler handler;
	public static void prepareHandler(){
		if (handler != null) {
			return;
		}
		new Thread(){
			@Override
			public void run() {
				Looper.prepare();
				handler=new AsyncHandler();
				Looper.loop();
			}
		}.start();
	}
	public static final byte SEND_DATA=0x01;//发送数据日志
	public static final byte RECEIVE_DATA=0x02;//接收日志
	public static final byte READ_OBDINFO=0x03;//
	public static final byte READ_DTC=0x04;//
	public static final byte READ_IURP=0x05;//
	public static final byte READ_IURP2=0x06;//
	public static final byte READ_QUICK_DIAGNOSE=0x07;//
	public static final byte READ_READY_STATE=0x08;//
	public static final byte READ_VDI_INFO =0x09;//
	public static final byte ACTIVE_SYSTEM =0x10;//
	public static final byte RESULT =0x11;//
	public static final byte INFO =0x12;//
	public static final byte OTHER =0x13;//
	public static class AsyncHandler extends Handler {
		@Override
		public void handleMessage( Message msg) {
			int what = msg.what;
			Object obj = msg.obj;
			StringBuilder builder=new StringBuilder();
			if (what==OTHER) {
				String strMsg= (String) obj;
				builder.append("\n");
				builder.append(strMsg);
				saveLog(builder.toString());
				return;
			}

			long l = System.currentTimeMillis();
			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = simpleDateFormat.format(l);
			switch (what) {
				case SEND_DATA:
					byte[] sendData= (byte[]) obj;
					builder.append("SEND_DATA:\t\t");
					builder.append(time);
					builder.append("\n");
//					builder.append(ByteUtilNew.bytesToHexString(sendData,sendData.length));
					break;
				case RECEIVE_DATA:
					byte[] receive= (byte[]) obj;
					builder.append("RECEIVE_DATA:\t\t");
					builder.append(time);
					builder.append("\n");
//					builder.append(ByteUtilNew.bytesToHexString(receive,receive.length));
					break;
				case RESULT:
					builder.append("RESULT:");
					builder.append(obj==null?"FAIL\t\t":"SUCCESS\t\t");
					builder.append(time);
					builder.append("\n");
					break;
				case INFO:
					builder.append((String) obj);
					break;
				case READ_OBDINFO:
					builder.append("读取ODB信息:\t\t");
					builder.append(time);
					break;
				case READ_DTC:
					builder.append("故障码:\t\t");
					builder.append(time);
					break;
				case READ_IURP:
					builder.append("IUPR数据:\t\t");
					builder.append(time);
					break;
				case READ_IURP2:
					builder.append("排放相关数据:\t\t");
					builder.append(time);
					break;
				case READ_QUICK_DIAGNOSE:
					builder.append("OBD快速检测:\t\t");
					builder.append(time);
					break;
				case READ_READY_STATE:
					builder.append("就绪状态:\t\t");
					builder.append(time);
					break;
				case READ_VDI_INFO:
					builder.append("time:\t\t");
					builder.append(time);
					String strMsg= (String) obj;
					builder.append("\n");
					builder.append(strMsg);
					break;
				case ACTIVE_SYSTEM:
					builder.append("激活系统:\t\t");
					builder.append(time);
					break;
			}
			saveLog(builder.toString());
		}
	}
	public static void saveLog(final byte[] data, final int type){
		if (!saveLog) {
			return;
		}
		if(handler==null){
			prepareHandler();
			return;
		}
		Message obtain = Message.obtain();
		obtain.what=type;
		obtain.obj=data;
		handler.sendMessage(obtain);
	}
	public static void init(){
		if (!saveLog) {
			return;
		}
		if(handler==null){
			prepareHandler();
			return;
		}
	}
	public static void saveLog(int type,Object msg){
		if (!saveLog) {
			return;
		}
		if(handler==null){
			prepareHandler();
			return;
		}
		i("插入日志 msg="+msg);
		Message obtain = Message.obtain();
		obtain.what=type;
		obtain.obj=msg;
		handler.sendMessage(obtain);
	}
	public static SimpleDateFormat formatter;

	public static String getTimeStramp() {
		if (formatter == null) {
			formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss:SSS");
		}
		return formatter.format(System.currentTimeMillis());
	}
	public static void saveLogWithTimeStramp(String msg){
		if (!saveLog) {
			return;
		}
		if(handler==null){
			prepareHandler();
			return;
		}
		i("插入日志 msg="+msg);

		msg="OTHER INFO\t\t"+getTimeStramp()+"\t\t"+msg;
		Message obtain = Message.obtain();
		obtain.what=OTHER;
		obtain.obj=msg;
		handler.sendMessage(obtain);
	}
	/**
	 * 将错误信息添加到log日志中
	 *
	 * @param ex
	 */
	public static void saveCrashInfo2Log(Throwable ex) {
		if (!saveLog) {
			return;
		}
		if (ex == null) {
			return;
		}

		StringBuffer sb = new StringBuffer();
		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		printWriter.close();
		String result = writer.toString();
		sb.append(result);
		saveLog(READ_VDI_INFO,sb.toString());
	}
	/**
	 * 将错误信息添加到log日志中
	 *
	 * @param ex
	 */
	public static String getCrashInfo(Throwable ex) {
		if (ex == null) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		printWriter.close();
		String result = writer.toString();
		sb.append(result);
		return sb.toString();
	}

	public static void saveLog(String log){
		if (!saveLog) {
			return;
		}
		log2File(log, FileUtils.getLogPath()+getLogFileName());
	}
	private static Handler logHandler;
	private static void checkLogHandler(){
		if (logHandler==null) {
			new Thread(){
				@Override
				public void run() {
					Looper.prepare();
					logHandler=new Handler();
					Looper.loop();

				}
			}.start();
		}
	}


	/**
	 * 以级别为 e 的形式输出msg信息,附带时间戳，用于输出一个时间段起始点
	 * 
	 * @param msg
	 *            需要输出的msg
	 */
	public static void msgStartTime(String msg) {
		mTimestamp = System.currentTimeMillis();
		if (!TextUtils.isEmpty(msg)) {
			e("[Started：" + mTimestamp + "]" + msg);
		}
	}

	/** 以级别为 e 的形式输出msg信息,附带时间戳，用于输出一个时间段结束点* @param msg 需要输出的msg */
	public static void elapsed(String msg) {
		long currentTime = System.currentTimeMillis();
		long elapsedTime = currentTime - mTimestamp;
		mTimestamp = currentTime;
		e("[Elapsed：" + elapsedTime + "]" + msg);
	}

	public static <T> void printList(List<T> list) {
		if (list == null || list.size() < 1) {
			return;
		}
		int size = list.size();
		i("---begin---");
		for (int i = 0; i < size; i++) {
			i(i + ":" + list.get(i).toString());
		}
		i("---end---");
	}

	public static <T> void printArray(T[] array) {
		if (array == null || array.length < 1) {
			return;
		}
		int length = array.length;
		i("---begin---");
		for (int i = 0; i < length; i++) {
			i(i + ":" + array[i].toString());
		}
		i("---end---");
	}
}
